package com.sunlee.app.api.context;

import com.sunlee.app.api.interceptor.AuthorizationInterceptor;
import com.sunlee.common.service.entity.CommonUserEntity;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 用户信息上下文
 *
 * @author sunlee
 * @date 2023-06-06
 */
public class UserContext {

    public static CommonUserEntity getUserInfo() {
        HttpServletRequest httpServletRequest = getHttpServletRequest();
        if (httpServletRequest != null) {
            Object userInfo = httpServletRequest.getAttribute(AuthorizationInterceptor.USER_INFO_KEY);
            return userInfo != null ? (CommonUserEntity) userInfo : null;
        }
        return null;
    }

    public static Long getUserId() {
        HttpServletRequest httpServletRequest = getHttpServletRequest();
        if (httpServletRequest != null) {
            Object userInfo = httpServletRequest.getAttribute(AuthorizationInterceptor.USER_KEY);
            return userInfo != null ? (Long) userInfo : null;
        }
        return null;
    }

    private static HttpServletRequest getHttpServletRequest() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        return requestAttributes == null ? null : ((ServletRequestAttributes) requestAttributes).getRequest();
    }
}
